package Threads.extra;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class produer_consumer1 {
    static ReentrantLock lock=new ReentrantLock();
    static Condition condition=lock.newCondition();
    public  static volatile int flag=0;
    public static void main(String[] args) {
        Thread t1=new Thread(()->{
            while (true) {
                lock.lock();
                while (flag != 0) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("1");
                flag = (flag + 1) % 3;
                condition.signalAll();
                lock.unlock();
            }
        });

        Thread t2=new Thread(()->{
            while (true) {
                lock.lock();
                while (flag != 1) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("2");
                flag = (flag + 1) % 3;
                condition.signalAll();
                lock.unlock();
            }
        });

        Thread t3=new Thread(()->{
            while (true) {
                lock.lock();
                while (flag != 2) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("3");
                flag = (flag + 1) % 3;
                condition.signalAll();
                lock.unlock();
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
